<link rel="import" href="/components/core-item/core-item.html">
<link rel="import" href="/components/core-menu/core-menu.html">
<link rel="import" href="/components/core-collapse/core-collapse.html">

<polymer-element name="nav-submenu" attributes="selected selectedItem label icon src active opened">
<template>

  <link rel="stylesheet" href="nav-submenu.css">

  <core-item src="{{src}}" label="{{label}}" icon="{{icon}}" class="{{ {'core-selected' : active} | tokenList}}" on-tap="{{activate}}">
    <content select=".item-content"></content>
  </core-item>

  <core-menu id="submenu" selected="{{selected}}" selectedItem="{{selectedItem}}">
    <content></content>
  </core-menu>

  <core-collapse target="{{$.submenu}}" opened="{{opened}}"></core-collapse>

</template>
<script>

  Polymer('nav-submenu', {

    publish: {
      active: {value: false, reflect: true}
    },

    opened: false,

    ready:function(){
      this.icon=this.active?"remove":"add";
    },

    get items() {
      return this.$.submenu.items;
    },

    hasItems: function() {
      return !!this.items.length;
    },

    unselectAllItems: function() {
      this.$.submenu.selected = null;
      this.$.submenu.clearSelection();
    },

    activeChanged: function() {
      if (this.hasItems()) {
        //this.opened = this.active;
      }
      if (!this.active) {
        this.unselectAllItems();
      }
    },
    
    toggle: function() {
      this.opened = !this.opened;
      this.icon = this.opened?"remove":"add";
    },

    activate: function() {
      this.toggle();
      //this.unselectAllItems();
    }
  });

</script>
</polymer-element>
